package com.mm.cloud.common.core.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.StandardReflectionParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.io.Serial;
import java.io.Serializable;
import java.lang.reflect.Method;

/**
 * Redis拼接Key
 *
 * @author mr
 * @since 2021-06-09
 */
@Slf4j
public class AspectHandleUtils implements Serializable {

    @Serial
    private static final long serialVersionUID = 1L;

    private AspectHandleUtils() {
    }

    private static final StandardReflectionParameterNameDiscoverer P_NAME_DISCOVERER = new StandardReflectionParameterNameDiscoverer();


    /**
     * 得到所有的方法参数签名
     *
     * @param method
     * @return
     */
    public static String[] getParameterNames(Method method) {
        return P_NAME_DISCOVERER.getParameterNames(method);
    }


    /**
     * 表达式获取参数
     *
     * @param pattern
     * @param arguments
     * @param method
     * @param clas
     * @param <T>
     * @return
     */
    public static <T> T parser(String pattern, Object[] arguments, Method method, Class<T> clas) {
        if (StringUtils.isNotBlank(pattern)) {
            String[] paramNames = getParameterNames(method);
            ExpressionParser parser = new SpelExpressionParser();
            Expression expression = parser.parseExpression(pattern);
            EvaluationContext context = new StandardEvaluationContext();
            for (int i = 0; i < arguments.length; i++) {
                context.setVariable(paramNames[i], arguments[i]);
            }
            if (StringUtils.isNotBlank(pattern)) {
                return expression.getValue(context, clas);
            }
        }
        return null;
    }
}
